package huas.ant.service.impl;

import huas.ant.constant.MessageConstant;
import huas.ant.entity.Admin;
import huas.ant.exception.AccountNotFoundException;
import huas.ant.exception.PasswordErrException;
import huas.ant.mapper.AdminMapper;
import huas.ant.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    /**
     * 查询是否存在该用户账号
     */
    @Override
    public Admin findByAdminAccount(String adminAccount) {
        Admin a = adminMapper.findByAdminAccount(adminAccount);
        return a;
    }

    /**
     * 注册添加管理员信息
     */
    @Override
    public void register(Admin admin) {
        String password = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
        admin.setPassword(password);
        //将密码进行MD5加密存储
        adminMapper.register(admin);
    }
    /**
     * 登录
     *
     * @return
     */
    @Override
    public Admin login(Admin admin) {
        //获取传递的数据
        String adminAccount = admin.getAdminAccount();
        String password = admin.getPassword();

        //查询数据库检查是否有该用户
        Admin a = adminMapper.findByAdminAccount(adminAccount);

        if(a == null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //MD5加密后无法解密
        //如果要校验需加密后比较加密的字符串
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(! password.equals(a.getPassword())){
            throw new PasswordErrException(MessageConstant.PASSWORD_ERROR);
        }
        //校验通过，返回该对象
        return a;
    }
}
